const PENDING = 'pending' // 等待
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected' // 失败

class MyPromise {
    constructor(executor) {
        try {
            // 传递的执行器会立即调用
            executor(this.resolve, this.reject)
        } catch (err) {
            this.reject(err)
        }
    }
    // promise 状态
    status = PENDING
    // 成功之后的值
    value = undefined
    // 失败之后的原因
    reason = undefined
    // 成功回调，需要存储多个回调函数
    successCallback = []
    // 失败回调，需要存储多个回调函数
    failCallback = []

    // resolve和reject使用箭头函数定义，是为了内部的this指向为当前的类
    resolve = value => {
        // 判断状态是否需要改变
        if (this.status !== PENDING) return
        this.status = FULFILLED
        // 保存成功之后的值
        this.value = value
        // 成功回调是否存在，存在就调用
        // this.successCallback && this.successCallback(this.value)
        while(this.successCallback.length) {
            this.successCallback.shift()()
        }
    }
    reject = reason => {
        // 判断状态是否需要改变
        if (this.status !== PENDING) return
        this.status = REJECTED
        // 保存失败之后的原因
        this.reason = reason
        // 失败回调是否存在，存在就调用
        // this.failCallback && this.failCallback(this.reason)
        while(this.failCallback.length) {
            this.failCallback.shift()()
        }
    }
    then(successCallback, failCallback) {
        // then不传递参数时的情况
        successCallback = successCallback ? successCallback : value => value
        failCallback = failCallback ? failCallback : reason => { throw reason }

        // 处理返回值
        const resolvePromise = (nextPromise, res, resolve, reject) => {
            // 返回值不能和本身相同
            if (nextPromise === res) {
                return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
            }
            if (res instanceof MyPromise) {
                // promise对象
                res.then(resolve, reject)
            } else {
                // 普通值
                resolve(res)
            }
        }
        // 判断状态
        const checkStatus = (resolve, reject) => {
            if (this.status === FULFILLED) {
                setTimeout(() => {
                    try {
                        let success = successCallback(this.value)
                        // 判断success是普通值还是promise对象
                        resolvePromise(nextPromise, success, resolve, reject)
                    } catch (err) {
                        reject(err)
                    }
                }, 0)
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        let fail = failCallback(this.reason)
                        // 判断success是普通值还是promise对象
                        resolvePromise(nextPromise, fail, resolve, reject)
                    } catch (err) {
                        reject(err)
                    }
                }, 0)
            } else {
                // 等待状态
                // 将成功回调和失败回调存起来
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let success = successCallback(this.value)
                            // 判断success是普通值还是promise对象
                            resolvePromise(nextPromise, success, resolve, reject)
                        } catch (err) {
                            reject(err)
                        }
                    }, 0)
                })
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let fail = failCallback(this.reason)
                            // 判断success是普通值还是promise对象
                            resolvePromise(nextPromise, fail, resolve, reject)
                        } catch (err) {
                            reject(err)
                        }
                    }, 0)
                })
            }
        }
        // 处理链式调用
        const nextPromise = new MyPromise(checkStatus)
        return nextPromise
    }
    finally(callback) {
        return this.then(value => {
            return MyPromise.resolve(callback()).then(() => value)
        }, reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason })
        })
    }
    catch(failCallback) {
        return this.then(undefined, failCallback)
    }
    static all(array) {
        let result = []
        let index = 0
        return new MyPromise((resolve, reject) => {
            const addData = (key, value) => {
                result[key] = value
                index++
                if (index === array.length) {
                    resolve(result)
                }
            }
            for (let i = 0; i < array.length; i++) {
                let current = array[i]
                if (current instanceof MyPromise) {
                    // promise对象
                    current.then(value => addData(i, value), reason => reject(reason))
                } else {
                    // 普通值
                    addData(i, array[i])
                }
            }
        })
    }
    static resolve(value) {
        if (value instanceof MyPromise) return value
        return new MyPromise((resolve) => resolve(value))
    }
}

module.exports = MyPromise